<?php
namespace app\api\controller;

use think\Cache;
use think\Controller;
use think\Request;
use app\common\model\Order as OrderModel;

class Order extends Controller
{   
    protected $order_model;

    public function _initialize(){
        parent::_initialize();
        $this->order_model = new OrderModel;
    }
    // 订单写入接口
    public function add_order(){
        if($this->request->isPost()){
            $data      = $this->request->param();
            $data['create_time']  = intval(time());
            $data['keyword'] = $data['name'] . $data['phone'] ;   // express

            if ($this->order_model->allowField(true)->save($data)) {
                $data_array = array(
                    'error'     => 0,
                    'msg'       => 'successful',
                    'data'      => '写入成功'
                );
                return json_encode($data_array,JSON_UNESCAPED_UNICODE);
            } else {
                $data_array = array(
                    'error'     => 333,
                    'msg'       => 'fail',
                    'data'      => '写入失败'
                );
                return json_encode($data_array,JSON_UNESCAPED_UNICODE);
            }
            // 读取写入数据库
        }else{
            $data_array = array(
                'error'     => 110,
                'msg'       => 'fail',
                'data'      => '请求错误'
            );
            return json_encode($data_array,JSON_UNESCAPED_UNICODE);
        }
    }

    public function place_order($token = 1){
        $ip = getIP();
        if($ip){
            $ipstr = str_replace('.','',$ip);
            if(Cache::has($ipstr)){
                //有缓存
                return json(['status' => -1 , 'msg' => 'Try again in 5 seconds']);
            }
            cache($ipstr,$ipstr,['expire' => 5]);
        }
        if(Request::instance()->isPost()){
            $data = Request::instance()->post();
            $result = $this->order_model->allowField(true)->save($data);
            if($result){
                return json(['status' => 1 , 'msg' => 'place order success']);
            }else{
                return json(['status' => -1 , 'msg' => 'place order error']);
            }
        }
    }
}